package com.seecen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.pojo.Product;
import com.seecen.pojo.UserAddress;
import com.seecen.service.UserAddressService;
import com.seecen.mapper.UserAddressMapper;
import com.seecen.utils.Result;
import com.seecen.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author 桃子
* @description 针对表【user_address】的数据库操作Service实现
* @createDate 2025-07-24 16:44:18
*/
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress>
    implements UserAddressService{


    @Autowired
    private UserAddressMapper userAddressMapper;
    @Override
    public Result selectAllAddress() {

        List<UserAddress> addressList = userAddressMapper.selectList(null);

        return Result.ok(addressList);
    }

    @Override
    public Result insertAddress(UserAddress userAddress) {
        // 参数校验
        if (userAddress == null) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }
        if (userAddress.getUserId() == null) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }
        if (userAddress.getReceiverName() == null || userAddress.getReceiverName().trim().isEmpty()) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }
        if (userAddress.getReceiverPhone() == null || userAddress.getReceiverPhone().trim().isEmpty()) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }
        if (userAddress.getDetailAddress() == null || userAddress.getDetailAddress().trim().isEmpty()) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        // 如果设置为默认地址，需要先将该用户其他地址设为非默认
        if (userAddress.getIsDefault() == 1) {
            LambdaUpdateWrapper<UserAddress> updateWrapper = new LambdaUpdateWrapper<>();
            // 等价于 WHERE user_id = ?
            updateWrapper.eq(UserAddress::getUserId, userAddress.getUserId())
                    // 设置 is_default = 0
                    .set(UserAddress::getIsDefault, 0);
            userAddressMapper.update(null, updateWrapper);
        }

        // 执行新增
        int rows = userAddressMapper.insert(userAddress);
        if (rows > 0) {
            return Result.ok( userAddress.getId());
        } else {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

    }

    @Override
    public Result deleteAddress(Integer id) {
        if (id == null) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        // 使用LambdaQueryWrapper查询地址是否存在
        LambdaQueryWrapper<UserAddress> queryWrapper = new LambdaQueryWrapper<>();
        // 等价于 WHERE id = ?
        queryWrapper.eq(UserAddress::getId, id);
        UserAddress address = userAddressMapper.selectOne(queryWrapper);

        if (address == null) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        // 执行删除
        int rows = userAddressMapper.deleteById(id);
        if (rows > 0) {
            return  Result.ok( null);
        } else {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

    }

    @Override
    public Result updateAddress(UserAddress userAddress) {
        // 参数校验
        if (userAddress == null || userAddress.getId() == null) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        // 使用LambdaQueryWrapper查询地址是否存在
        LambdaQueryWrapper<UserAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAddress::getId, userAddress.getId());
        UserAddress existingAddress = userAddressMapper.selectOne(queryWrapper);

        if (existingAddress == null) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        // 如果更新为默认地址，使用LambdaWrapper将同用户其他地址设为非默认
        if (userAddress.getIsDefault() != null && userAddress.getIsDefault() == 1) {
            LambdaUpdateWrapper<UserAddress> updateWrapper = new LambdaUpdateWrapper<>();
            // 条件：同用户 + 不是当前地址
            updateWrapper.eq(UserAddress::getUserId, existingAddress.getUserId())
                    .ne(UserAddress::getId, userAddress.getId())
                    // 设置为非默认
                    .set(UserAddress::getIsDefault, 0);
            userAddressMapper.update(null, updateWrapper);
        }

        // 执行地址更新（使用MyBatis-Plus的updateById方法，基于主键更新）
        int rows = userAddressMapper.updateById(userAddress);
        if (rows > 0) {
            return Result.ok(null);
        } else {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }
    }

    @Override
    public Result selectByUid(Integer userId) {
        // 判空处理
        if (userId == null) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        // 创建Lambda查询条件构造器
        LambdaQueryWrapper<UserAddress> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件：userId等于传入的参数，并且排除已删除的记录
        queryWrapper.eq(UserAddress::getUserId, userId)
                .eq(UserAddress::getIsDeleted, 0);

        // 执行查询，查询该用户的所有地址
        List<UserAddress> addressList = userAddressMapper.selectList(queryWrapper);

        if (addressList != null && !addressList.isEmpty()) {
            return Result.ok(addressList);
        } else {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }
    }

    @Override
    public Result selectByid(Integer id) {
        // 判空处理
        if (id == null) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        // 创建Lambda查询条件构造器
        LambdaQueryWrapper<UserAddress> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件：id等于传入的参数，并且排除已删除的记录
        queryWrapper.eq(UserAddress::getId, id)
                .eq(UserAddress::getIsDeleted, 0);

        // 执行查询，获取单个地址信息
        UserAddress userAddress = userAddressMapper.selectOne(queryWrapper);

        if (userAddress != null) {
            return Result.ok(userAddress);
        } else {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }
    }

    @Override
    @Transactional
    public Result setDefaultAddressById(Integer id) {
        // 1. 先查询该地址的信息，获取对应的userId
        UserAddress address = getById(id);
        if (address == null) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        Long userId = address.getUserId();

        // 2. 将该用户的所有地址设为非默认（isDefault = 0）
        LambdaUpdateWrapper<UserAddress> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserAddress::getUserId, userId)
                .set(UserAddress::getIsDefault, 0);
        baseMapper.update(null, updateWrapper);

        // 3. 将指定ID的地址设为默认（isDefault = 1）
        LambdaUpdateWrapper<UserAddress> defaultWrapper = new LambdaUpdateWrapper<>();
        defaultWrapper.eq(UserAddress::getId, id)
                .set(UserAddress::getIsDefault, 1);
        int rows = baseMapper.update(null, defaultWrapper);

        // 4. 根据更新结果返回相应信息
        if (rows > 0) {
            return Result.ok(null);
        } else {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }
    }
}




